//
//  TYPZViewController.m
//  Estate
//
//  Created by heyong on 16/5/27.
//  Copyright © 2016年 ttsx. All rights reserved.
//

static CGFloat const ButtonHeight = 40;

#import "TYPZFHViewController.h"
#import "TYPZJXViewController.h"
#import "TYPZRViewController.h"
#import "TYPZZLViewController.h"
#import "TYPZWLViewController.h"
#import "SegmentViewController.h"
#import "Site_01.h"

#import "TYPZViewController.h"


@interface TYPZViewController ()
{
    FMDatabase *_db;
    DBHelper *_helper;
    SegmentViewController *vc;
}

/**数据模型*/
@property (strong ,nonatomic)Site_01 *site;

//新增数据记录id
@property (copy, nonatomic)NSString *recordId;

@property (assign, nonatomic)BOOL edit;

@property (strong, nonatomic)TYPZZLViewController *ZLCtr;
@property (strong, nonatomic)TYPZRViewController *RCtr;
@property (strong, nonatomic)TYPZJXViewController *JXCtr;
@property (strong, nonatomic)TYPZWLViewController *WLCtr;
@property (strong, nonatomic)TYPZFHViewController *FHCtr;

@end

@implementation TYPZViewController

- (Site_01 *)site {
    if(_site==nil) {
        _site = [[Site_01 alloc]init];
    }
    return _site;
}

// 解决查看后 再次添加 无法显示保存按钮的bug
- (void)setFlag:(NSString *)flag {
    _flag = flag;
    if ([self.flag isEqualToString:@"addty"]) {
        self.edit=YES;
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
        
    // 日记页面链接进入
    } else if ([self.flag isEqualToString:@"look"]) {
        self.edit = NO;
        
    // 旁站列表页进入
    } else if ([self.flag isEqualToString:@"upRecord"]) {
    
        //判断是否超过旁站结束时间 或者 日记提取了此条记录
//        self.edit=[LSUtility isSameDay:self.site.createTime];
        self.edit=[LSUtility siteEditForendTimeAndSiteRecordId:self.site.recordId beginTine:self.site.createTime endTime:self.site.endTime];
        
        if (self.edit) {
            //添加右上方提交按钮
            self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
            
        } else {
            self.navigationItem.rightBarButtonItem = nil;
        }
    }
}

- (void)setSideId:(NSString *)sideId {
    _sideId = sideId;
    WEAKSELF
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *helper=[DBHelper help];
    NSDictionary *supData = [[helper DataBase:db selectKeyTypes:@{@"RECORD_NUMBER":@"text",@"RECORD_INFO":@"text",@"RECORD_FILE_PATH":@"text",@"CREATE_TIME":@"text",@"ADDRESS_ID":@"text",@"ADDRES_INFO":@"text",@"WEATHER":@"text"} fromTable:WORK_RECORD whereCondition:@{@"ID":sideId}]lastObject];

    NSString *dataJson = supData[@"RECORD_INFO"];
    //得到附件数组
    NSString *fileJson = DEFISNUL(supData[@"RECORD_FILE_PATH"]);
    weakSelf.site.fileArray=[LSUtility dictionaryWithJsonString:fileJson];
    //详细数据转字典
    NSDictionary *siteDic=[LSUtility dictionaryWithJsonString:dataJson];
    
    weakSelf.site.recordId = _sideId;
        //位置
    weakSelf.site.locationInfo=DEFISNUL(siteDic[@"locationInfo"]);
    weakSelf.site.locationId=DEFISNUL(supData[@"ADDRESS_ID"]);
    weakSelf.site.location=DEFISNUL(supData[@"ADDRES_INFO"]);
    
    //基本信息
    NSDictionary *XXDic=siteDic[@"基本信息"];
    weakSelf.site.beginTime=XXDic[@"开始时间"];
    weakSelf.site.endTime=XXDic[@"结束时间"];
    weakSelf.site.weather=XXDic[@"天气"];
    weakSelf.site.danwei=XXDic[@"施工单位"];
    weakSelf.site.jlName=XXDic[@"旁站监理人"];
    weakSelf.site.diqu=XXDic[@"地区"];
    weakSelf.site.number=supData[@"RECORD_NUMBER"];
    
    //人
    NSDictionary *RDic=siteDic[@"人"];
    weakSelf.site.createTime=supData[@"CREATE_TIME"];
    weakSelf.site.gongbanNum=RDic[@"工班人数"];
    weakSelf.site.zaigangNum=RDic[@"施工单位质检在岗人员"];
    weakSelf.site.guanliNum=RDic[@"管理人数"];
    weakSelf.site.chouNum=RDic[@"抽查"];
    weakSelf.site.isR=RDic[@"是否满足施工组织需要"];
    weakSelf.site.teshuChiNum=RDic[@"特殊工种持证上岗情况"];
    weakSelf.site.teshuNum=RDic[@"特殊工种"];
    
    //机械
    NSDictionary *JXDic=siteDic[@"机械"];
    weakSelf.site.jixie_1=JXDic[@"设备1名称"];
    weakSelf.site.jixie_2=JXDic[@"设备2名称"];
    weakSelf.site.jixie_3=JXDic[@"设备3名称"];
    weakSelf.site.jixie1_num=JXDic[@"设备1台数"];
    weakSelf.site.jixie2_num=JXDic[@"设备2台数"];
    weakSelf.site.jixie3_num=JXDic[@"设备3台数"];
    weakSelf.site.isJ=JXDic[@"是否满足施工组织需要"];
    weakSelf.site.isJ_1=JXDic[@"上述各项机械设备运转是否正常"];
    
    // 物料
    NSDictionary *WLDic=siteDic[@"物料"];
    weakSelf.site.wl_text_1=WLDic[@"设计使用材料情况"];
    weakSelf.site.wl_text_2=WLDic[@"对到场材料使用情况的抽查"];
    weakSelf.site.wl_text_3=WLDic[@"见证取样和送检的情况"];
    
    // 法环
    NSDictionary *FHDic=siteDic[@"法环"];
    weakSelf.site.isfh_1=FHDic[@"是否符合冬雨季施工条件"];
    weakSelf.site.isfh_2=FHDic[@"是否按照冬雨季施工方案组织施工"];
    weakSelf.site.fh_text_1=FHDic[@"检查施工方案执行情况"];
    weakSelf.site.fh_text_2=FHDic[@"发现的问题及处理情况"];
    
    //工序
    NSDictionary *XXDic_1=XXDic[@"工序"];
    weakSelf.site.otherAddress=XXDic_1[@"关键工序"];
    weakSelf.site.duan=XXDic_1[@"段"];
    weakSelf.site.ceng=XXDic_1[@"层"];
    weakSelf.site.lou=XXDic_1[@"楼"];
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"pzTableRefresh" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"旁站-通用-记录";
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];

    _db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    _helper = [DBHelper help];
}

- (void)viewWillAppear:(BOOL)animated {
    //根据flag 选择性刷新页面
    if(self.isSubStr!=nil){
        [self createsliderBtn];
    }
}

- (void)viewDidDisappear:(BOOL)animated{
    //清除flag：确保进入二级页面后 返回数据不会清空
    self.isSubStr=nil;
}

#pragma mark - 创建Slider按钮
- (void)createsliderBtn {
    WEAKSELF
    if (vc) {
        [vc.view removeFromSuperview];
    }
    vc = [[SegmentViewController alloc]init];
    vc.height = DEF_SCREEN_HEIGHT - 108;
    vc.titleArray = @[@"基本资料", @"人", @"机械", @"物料", @"法/环"];
    weakSelf.ZLCtr=[[TYPZZLViewController alloc]init];
    weakSelf.RCtr=[[TYPZRViewController alloc]init];
    weakSelf.JXCtr=[[TYPZJXViewController alloc]init];
    weakSelf.WLCtr=[[TYPZWLViewController alloc]init];
    weakSelf.FHCtr=[[TYPZFHViewController alloc]init];
    
    //查看页面
    if(![self.flag isEqualToString:@"addty"]){
        //查看详情 设置数据model
        weakSelf.ZLCtr.site=weakSelf.site;
        weakSelf.RCtr.site=weakSelf.site;
        weakSelf.JXCtr.site=weakSelf.site;
        weakSelf.WLCtr.site=weakSelf.site;
        weakSelf.FHCtr.site=weakSelf.site;
        
        weakSelf.ZLCtr.isEdit=self.edit;
        weakSelf.RCtr.isEdit=self.edit;
        weakSelf.JXCtr.isEdit=self.edit;
        weakSelf.WLCtr.isEdit=self.edit;
        weakSelf.FHCtr.isEdit=self.edit;
        
    } else {
        //添加页面 允许编辑
        weakSelf.ZLCtr.isEdit=YES;
        weakSelf.RCtr.isEdit=YES;
        weakSelf.JXCtr.isEdit=YES;
        weakSelf.WLCtr.isEdit=YES;
        weakSelf.FHCtr.isEdit=YES;
    }
    
    NSMutableArray *controlArray = [[NSMutableArray alloc]initWithObjects:weakSelf.ZLCtr,weakSelf.RCtr,weakSelf.JXCtr,weakSelf.WLCtr, weakSelf.FHCtr,nil];
    //设置选中字体颜色
    vc.titleSelectedColor = [TTTheme defaultManger].defaultColor;
    //设置子视图
    vc.subViewControllers = controlArray;
    //标签栏背景色
    vc.headViewBackgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    //非选中状态下标签字体大小
    vc.fontSize=14.;
    //选中下划线颜色
    vc.bottomLineColor=[TTTheme defaultManger].defaultColor;
    vc.buttonWidth = DEF_SCREEN_WIDTH/5;
    vc.buttonHeight = ButtonHeight;
    [vc initSegment];
    [vc addParentController:self];
}

#pragma  mark- 保存方法
- (void)clickSave {
    WEAKSELF
    if([self.ZLCtr.dataDic[@"施工单位"] isEqual:@""]){
        [LSUtility showToastWithMessage:@"请选择施工单位" inView:self.view Andtime:1.];
    }
    else if(weakSelf.ZLCtr.locationDic[@"locationInfo"]==nil)
    {
          [LSUtility showToastWithMessage:@"位置信息不能为空" inView:self.view Andtime:1.];
    }
    else
    {
        if([self.flag isEqualToString:@"addty"]){
            [self addDataBase];
            
        } else if ([self.flag isEqualToString:@"upRecord"]){
            [self upDataBase];
            
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark - 新增数据
- (void)addDataBase {
    WEAKSELF
    self.recordId = [NSUUID UUID].UUIDString;
    NSMutableArray *fileArr = [self insertAttachment:self.recordId];
    NSString *recordInFoPath=[LSUtility dictionaryToJson_2:fileArr];
    
    // 数据结构法，存入数据库
    NSDictionary *dataDic = @{@"人":weakSelf.RCtr.dataDic,@"法环":weakSelf.FHCtr.dataDic,@"基本信息":weakSelf.ZLCtr.dataDic,@"物料":weakSelf.WLCtr.dataDic,@"机械":weakSelf.JXCtr.dataDic,@"locationInfo":weakSelf.ZLCtr.locationDic[@"locationInfo"]};
    
    NSString *diqu=[weakSelf.ZLCtr.dataDic objectForKey:@"地区"];
    NSString *weather=[weakSelf.ZLCtr.dataDic objectForKey:@"天气"];
    NSString *wea=[NSString stringWithFormat:@"%@/%@",diqu,weather];
    ///标题，楼层段工序
    NSDictionary *dic= weakSelf.ZLCtr.dataDic[@"工序"];
    NSString *louStr=dic[@"楼"];
    NSString *cStr=dic[@"层"];
    NSString *dStr=dic[@"段"];
    NSString *gjStr=dic[@"关键工序"];
    NSString *titleStr=[NSString stringWithFormat:@"%@楼%@层%@段%@工序",louStr,cStr,dStr,gjStr];
    
    //字典转json   RECORD_INFO
    NSString *strData=[LSUtility dictionaryToJson:dataDic];
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if([role isEqualToString:@"USER_01"]){
        role=@"0";
    }else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]){
        role=@"1";
    }
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    //得到开始时间 存入创建时间
    NSString *createTime=weakSelf.ZLCtr.dataDic[@"开始时间"];
    pragameDic=@{
                 @"ID":self.recordId,
                 @"PRO_ID":PROID,
                 @"RECORD_USER":USERID,
                 @"RECORD_MASTER":@"",
                 @"RECORD_SUPERVISION_USER":@"",
                 @"WEATHER":wea,
                 @"ADDRESS_ID":weakSelf.ZLCtr.locationDic[@"locationId"],
                 @"ADDRES_INFO":weakSelf.ZLCtr.locationDic[@"location"],
                 @"RECORD_TYPE":@"RECORD_02_01",
                 @"RECORD_TITLE":@"通用旁站",
                 @"RECORDONTENT":@"",
                 @"RECORD_FILE_PATH":recordInFoPath,
                 @"RECORD_INFO":strData,
                 @"STATE":role,
                 @"RECORD_NUMBER":@"",
                 @"EXTEND_INFO":titleStr,
                 @"CREATE_USER_NAME":@"anonymous",
                 @"CREATE_TIME":createTime,
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    
    BOOL isAdd=[_helper DataBase:_db insertKeyValues:pragameDic intoTable:WORK_RECORD];
    if(isAdd){
        NSLog(@"旁站-通用新增成功");
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        NSLog(@"旁站-通用新增失败");
    }
}

// 附件存入
-(NSMutableArray *)insertAttachment:(NSString *)recordIds {
    WEAKSELF
    NSMutableArray *recordFileArr = [NSMutableArray array];
    //人附件存入附件表
    weakSelf.RCtr.selectedAssetURLs = [weakSelf.RCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    if (weakSelf.RCtr.selectedAssetURLs.count>0) {
        NSMutableArray *rFileArr = [LSUtility insertAttachmentSiteFromArray:weakSelf.RCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_01" andChildType:@"RECORD_02_SIDE_01"];
        
        for (NSDictionary *dic in rFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //机械附件存入
    weakSelf.JXCtr.selectedAssetURLs = [weakSelf.JXCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    if(weakSelf.JXCtr.selectedAssetURLs.count>0){
        NSMutableArray *JXFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.JXCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_01" andChildType:@"RECORD_02_SIDE_02"];
        for (NSDictionary *dic in JXFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //物料附件存入
    weakSelf.WLCtr.selectedAssetURLs = [weakSelf.WLCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    if(weakSelf.WLCtr.selectedAssetURLs.count>0){
        NSMutableArray *wlFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.WLCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_01" andChildType:@"RECORD_02_SIDE_03"];
        for (NSDictionary *dic in wlFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //法环附件存入
    weakSelf.FHCtr.selectedAssetURLs = [weakSelf.FHCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        if(weakSelf.FHCtr.selectedAssetURLs.count>0){
        NSMutableArray *fhFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.FHCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_01" andChildType:@"RECORD_02_SIDE_04"];
        for (NSDictionary *dic in fhFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    return recordFileArr;
}

#pragma mark - 修改数据
- (void)upDataBase {
    WEAKSELF
    NSMutableArray *fileArr = [self insertAttachment:_sideId];
    NSString *recordInFoPath = [LSUtility dictionaryToJson_2:fileArr];
    if (self.edit) {
        //数据结构法，存入数据库
        NSDictionary *dataDic = @{@"人":weakSelf.RCtr.dataDic,@"法环":weakSelf.FHCtr.dataDic,@"基本信息":weakSelf.ZLCtr.dataDic,@"物料":weakSelf.WLCtr.dataDic,@"机械":weakSelf.JXCtr.dataDic,@"locationInfo":weakSelf.ZLCtr.locationDic[@"locationInfo"]};
        //字典转json RECORD_INFO
        NSString *strData=[LSUtility dictionaryToJson:dataDic];
        
        ///标题，楼层段工序
        NSDictionary *dic= weakSelf.ZLCtr.dataDic[@"工序"];
        NSString *louStr=dic[@"楼"];
        NSString *cStr=dic[@"层"];
        NSString *dStr=dic[@"段"];
        NSString *gjStr=dic[@"关键工序"];
        NSString *titleStr=[NSString stringWithFormat:@"%@楼%@层%@段%@工序",louStr,cStr,dStr,gjStr];
        
        NSString *diqu=[weakSelf.ZLCtr.dataDic objectForKey:@"地区"];
        NSString *weather=[weakSelf.ZLCtr.dataDic objectForKey:@"天气"];
        NSString *wea=[NSString stringWithFormat:@"%@/%@",diqu,weather];

        //字段及对应值
        NSDictionary *pragameDic=[NSDictionary dictionary];
        pragameDic=@{
                     @"RECORD_INFO":strData,
                     @"EXTEND_INFO":titleStr,
                     @"WEATHER":wea,
                     @"MODIFY_TIME":[LSUtility nowTime],
                     @"ADDRESS_ID":weakSelf.ZLCtr.locationDic[@"locationId"],
                     @"ADDRES_INFO":weakSelf.ZLCtr.locationDic[@"location"],
                     @"RECORD_FILE_PATH":recordInFoPath,
                     @"LOCAL_MODIFY_STATE":@"MOD",
                     };
        
        [_helper DataBase:_db updateTable:WORK_RECORD setKeyValues:pragameDic whereCondition:@{@"ID":_sideId}];

        NSNotification *notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
    } else {
        //无法编辑，不做任何操作
    }
    [self.navigationController popViewControllerAnimated:YES];
}


@end

